package com.beerandjesus.sportofkings.handicapper.profile.resolver;

import com.beerandjesus.sportofkings.handicapper.model.KeyTrainerStatistics;
import com.beerandjesus.sportofkings.handicapper.model.TrainerJockeyOwner;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.Horse;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.HorseRace;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.KeyTrainerStatisticsCategory;
import com.beerandjesus.sportofkings.handicapper.model.brisnet.singlefile.PastPerformance;
import com.beerandjesus.sportofkings.handicapper.profile.AnalysisProfile;
import com.beerandjesus.sportofkings.handicapper.profile.AnalysisProfileBuilder;
import org.apache.commons.lang.StringUtils;

import java.util.List;

import static com.beerandjesus.sportofkings.handicapper.profile.AnalysisProfile.Type.CLAIMED_BY_WINNING_TRAINER;
import static com.beerandjesus.sportofkings.handicapper.profile.AnalysisProfileBuilder.analysisProfile;

/**
 * Date: 7/3/13
 * Time: 5:35 PM
 */
public class ClaimedByWinningTrainerProfileResolver implements AnalysisProfileResolver {
    public AnalysisProfile resolve(HorseRace race, Horse horse) {
        // Must have been claimed in last race
        List<PastPerformance> pps = horse.getPastPerformances();
        if (pps == null || pps.size() == 0) {
            return null;
        }
        String claimedCode = pps.get(0).getClaimedCode();
        if (StringUtils.isEmpty(claimedCode)) {
            return null;
        }
        // Trainer must win 20% or better with 1st starters after claim
        TrainerJockeyOwner tjo = horse.getTrainerJockeyOwner();
        if (tjo == null) {
            return null;
        }
        List<KeyTrainerStatistics> stats = tjo.getKeyTrainerStatistics();
        if (stats == null || stats.size() == 0) {
            return null;
        }
        for (KeyTrainerStatistics stat : stats) {
            if (KeyTrainerStatisticsCategory.STAT_1ST_AFTER_CLM.equals(stat.getCategory())) {
                Double winPercentage;
                try {
                    winPercentage = Double.parseDouble(stat.getWinPercentage());
                } catch (Exception e) {
                    return null;
                }
                if (winPercentage > 20d) {
                    return analysisProfile(CLAIMED_BY_WINNING_TRAINER, winPercentage.intValue());
                }
            }
        }
        return null;
    }
}
